<template>
  <div class="app-container">
    <el-row :gutter="5" class="app-container-content" style="flex-wrap: nowrap;">
      <div style="height:100%;width: 400px;" class="mr5">
        <el-card class="interface-tree" v-loading="loading">
          <el-row :gutter="5">
            <el-form :model="queryParams" :style="{width: '100%',margin:'5px 3px 1px 5px'}" ref="queryRef">
              <el-row :gutter="12">
                <el-col :span="18">
                  <el-form-item label-width="0px" label="" prop="infName">
                    <el-input
                        v-model="queryParams.infName"
                        placeholder="请输入接口名称或路径"
                        clearable
                        @keyup.enter="handleQuery"
                        :style="{width: '100%'}"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-button
                      type="primary"
                      style="margin: 5px 3px 1px 5px"
                      icon="Sort"
                      @click="toggleExpandAll"
                      v-hasPermi="['testmanage:infManage:Expand']"
                  >展开/折叠
                  </el-button>
                </el-col>
                <!--                                <el-col :span="4">
                                                    <el-form-item>
                                                        <el-button type="primary" icon="Search" style="margin: 5px 3px 3px 3px"
                                                                   v-hasPermi="['testmanage:infManage:list']" @click="handleQuery">搜索
                                                        </el-button>
                                                    </el-form-item>
                                                </el-col>-->

              </el-row>
            </el-form>
          </el-row>
          <infTableV2 ref="treeDataV2" :data="InfList" @clickRow="rowData=>{handleSelectionChange([rowData])}"
                      @handleAddInf="handleAddInf" @handleAddCata="handleAddCata" @handleCopy="handleCopy"
                      @handleDeleteInfById="handleDeleteInfById"
                      :currentTab="tabsValue" :isExpandAll="isExpandAll"
          />
        </el-card>
      </div>
      <div style="height:100%;flex: 1;overflow: hidden;" class="interface-container">
        <div class="api-environment-input">
          <span style="font-size:12px;" class="el-form-item__label"></span>
          <baseCombox url="/tsstEnv/list"
                      valueField="envId" labelField="envName"
                      style="width: 200px"
                      clearable
                      @change="handleEnvChange"
                      :queryParam="{envStatus: '1'}"
                      placeholder="请选择环境" v-model="globalEnv"/>
          <el-button
              type="primary"
              style="margin: 3px 3px"
              icon="Edit"
              @click="handleAddEnv"
              v-hasPermi="['testmanage:env:insert']"
          ></el-button>
        </div>
        <TabList style="height:100%" v-model="tabsValue" @tab-remove="removeTab" class="demo-tabs page-tabs"
                 :tabList="infTabs" nameValue="infId" lableValue="infName">
          <template #default="{item}">
            <InfTab :form="item" :globalEnv="globalEnv" :infOptions="infOptions" @getList="getList" @refresh="refresh"
                    @jumpToInf="jumpToInf" @removeTab="removeTab" :isShow="tabsValue==item.infId">
            </InfTab>
          </template>
        </TabList>
      </div>
    </el-row>
  </div>
</template>

<script setup name="Inf">
import JsonEditorVue from 'json-editor-vue3'
import {getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs, watch} from "vue";

const {proxy} = getCurrentInstance();
import store from '@/store'
import useUserStore from "../../../store/modules/user";
import {
  listInf,
  listByCondition,
  getInf,
  queryInfAll,
  querySstInfAll,
  delInf,
  addInf,
  updateInf,
  listInfExcludeChild,
  addReport, copyInf, childrenList
} from "@/api/testmanage/sstinf";
import {div, isNotVoid, isVoid, mul} from "@/utils/util";
import InfTab from '@/views/testmanage/interfacesmanage/infTab'
import {useRouter} from "vue-router";
import TabList from '@/components/TabList'
import infTableV2 from './infTable.vue/infTableV2.vue';
import {listDefaultEnv, updateEnv} from "@/api/testmanage/env";

const router = useRouter();
const {
  sys_normal_disable,
  accStatus,
  infProperty,
  infMethod
} = proxy.useDict("sys_normal_disable", "accStatus", "infProperty", "infMethod");

const InfList = ref([]);
const infTabs = ref([]);
const loading = ref(true);

const infOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);


const addInfId = ref(10000)
const infId = ref();

const rowSelect = ref(true);
const selectRowData = ref([]);
const delDisable = ref(false);
const jsonEditView = ref(true);
const tabsValue = ref('')
const globalEnv = ref('')

const data = reactive({
  form: {
    infCode: '',
    infName: '',
    infType: '',
    infUrl: '',
    infMethod: 'POST',
    infRequest: '',
    infEnv: '',
    infProperty: '',
    contentType: 'application/json',
    authorization: '',
    cookie: 'uToken=3b89fa6880c683a49d55bd7e1ba2ea7b',
    parentId: '',
    ancestors: '',
    leader: '1',
    delFlag: '0',
    orderNum: 0,
    status: "0",
    concurrency: "10",
    round: "10",
    paramType: '',
    infResponse: '',
    infResponseJson: '',
    consumeTime: '',
    success: '',
    mcs: '',
    currentMode: 'code',
    reportName: '',
    reportType: 'S',
    reportVersion: '',
    requestTime: '',
    responseTime: '',
    infRequestJson: '',
    timeOut: '',
    variableSwitch: '0',
    variableType: '全局变量',
    variableName: 'AUTHORIZATION',
    variableEl: '$.result',
    variableCustom: '$',
  },
  queryParams: {
    infName: undefined
  },
});
const {queryParams, form} = toRefs(data);

function reset() {
  form.value = {
    infCode: '',
    infName: '',
    infType: '',
    infUrl: '',
    infMethod: 'POST',
    infRequest: '',
    infEnv: '',
    infProperty: '',
    contentType: 'application/json',
    authorization: '',
    cookie: '',
    parentId: '',
    ancestors: '',
    leader: '1',
    delFlag: '0',
    orderNum: 0,
    status: "0",
    concurrency: "10",
    round: "10",
    paramType: '',
    infResponse: '',
    infResponseJson: '',
    consumeTime: '',
    success: '',
    mcs: '',
    currentMode: 'code',
    reportName: '',
    reportType: 'S',
    reportVersion: '',
    requestTime: '',
    responseTime: '',
    infRequestJson: '',
    variableSwitch: '0',
    variableType: '全局变量',
    variableName: 'AUTHORIZATION',
    variableEl: '$.result',
    variableCustom: '$',
  };
  proxy.resetForm("cataMainRef");
  proxy.resetForm("cataInfoRef");
  proxy.resetForm("infMainRef");
  proxy.resetForm("infBaseRef");
  proxy.resetForm("infAfterRef");
}

watch(() => queryParams.value.infName, (nv, ov) => {
  if (nv !== ov) {
    handleQuery()
  }
})

function resetInfRequest() {
  jsonEditView.value = false;
  form.value.currentMode = 'code';
  jsonEditView.value = true;
}

/** 查询接口列表 */
const infListFlatten = ref([])

function getList() {
  loading.value = true;
  listByCondition(queryParams.value).then(response => {
    infListFlatten.value = response.data
    InfList.value = proxy.handleTree(response.data, "infId");
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/**
 * 新增环境跳转
 * */
function handleAddEnv(row) {
  let url = '/pricing/Env';
  let realUrl = url.replace("/index", "")
  router.push({
    path: realUrl
  })
}
function handleEnvChange(val){

}
/**
 * 初始化默认环境
 * */
function getDefaultEnv() {
  let data = {'isDefault': '1'}
  listDefaultEnv(data).then(response => {
    if (response.rows.length === 1) {
       globalEnv.value = String(response.rows[0].envId);
    }
  });
}
getDefaultEnv();


/** 新增目录操作 */
async function handleAddCata(row) {
  reset();
  form.value.infType = 'C';
  form.value.infName = '新建目录'
  await handleAdd(row);
}

/** 新增接口操作 */
async function handleAddInf(row) {
  reset();
  form.value.infType = 'I';
  form.value.infName = '新建接口'
  await handleAdd(row);
}

async function handleAdd(row) {
  form.value.infId = addInfId.value
  addInfId.value++
  await listInf().then(response => {
    infOptions.value = proxy.handleTree(response.data, "infId");
  });
  if (row.infId !== undefined) {
    form.value.parentId = row.infId;
  } else {
    if (infId.value !== undefined) {
      form.value.parentId = infId.value[0];
    }
  }
  addInfTab(form.value)
}

const addInfTab = (data) => {
  if (infTabs.value.length >= 20) {
    infTabs.value.shift();
  }
  data.infNameInput = data.infName;
  infTabs.value.push(data)
  tabsValue.value = data.infId
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

function handleDeleteInfById(row) {
  proxy.$modal.confirm('是否确认删除名称为"' + row.infName + '"的数据项?').then(function () {
    return delInf(row.infId);
  }).then(() => {
    removeTab(row.infId)
    getList();
    proxy.$modal.msgSuccess("删除成功");
    // let data = {infId: row.parentId};
    // queryInfDetail(data);
  }).catch(() => {

  });
}

/** 查询 */
async function queryInfDetail(row) {
  reset();
  const queryData = {
    infType: 'C'
  }
  await listInf(queryData).then(response => {
    infOptions.value = proxy.handleTree(response.data, "infId");
    getInf(row.infId).then(response => {
      form.value = response.data;
      form.value.variableSwitch = String(response.data.variableSwitch);
      try {
        form.value.infRequestJson = JSON.parse(response.data.infRequest);
      } catch (error) {
        form.value.infRequestJson = response.data.infRequest
        console.error('请求参数不是json')
      }
      tabsValue.value = form.value.infId
      for (var i = 0; i < infTabs.value.length; i++) {
        if (infTabs.value[i].infId === form.value.infId) {
          return
        }
      }
      addInfTab(form.value)
    });
  });
}

/** 选中数据 */
function handleSelectionChange(selection) {
  rowSelect.value = selection.length != 1;
  infId.value = selection.map(item => item.infId);
  selectRowData.value = selection;
  if (selection.length > 0 && selection[0].parentId != 0) {
    delDisable.value = false;
  } else {
    delDisable.value = true;
  }
  if (selection.length == 1) {
    let data = selection[0];
    queryInfDetail(data);
  }
}

function jumpToInf(id) {
  handleRouter(id)
}

function handlefirst() {
  getInf(1).then(response => {
    let data = response.data
    addInfTab(data)
  });
}

//复制接口
function handleCopy(row) {
  copyInf(row.infId).then(response => {
    if (response.code == 200) {
      proxy.$modal.msgSuccess("复制成功");
      getList()
    } else {
      proxy.$modal.msgSuccess("复制失败");
    }
  });
}

//点击分配用户按钮
onMounted(() => {
  setTimeout(() => {
    // loading.value = false;
  }, 300);
  window.onresize = function temp() {
    //screenHeight.value = document.documentElement.clientHeight - 350 + "px;";
  };
})

onMounted(() => {
  if (proxy.isNotVoid(router.currentRoute.value.query.infId)) {
    handleRouter(router.currentRoute.value.query.infId)
  }
})

function handleRouter(infId) {
  const row = {
    infId: infId
  }
  queryInfDetail(row)
}

function removeTab(targetValue) {
  const tabs = infTabs.value
  let activeName = tabsValue.value
  if (activeName == targetValue) {
    tabs.forEach((tab, index) => {
      if (tab.infId === targetValue) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        console.log(nextTab)
        if (nextTab) {
          activeName = nextTab.infId
        }
      }
    })
  }
  tabsValue.value = activeName
  infTabs.value = tabs.filter((tab) => tab.infId !== targetValue)
}

function refresh(replace) {
  let data = tabsValue.value
  for (var i = 0; i < infTabs.value.length; i++) {
    if (infTabs.value[i].infId == data) {
      infTabs.value[i].infId = replace
    }
  }
  tabsValue.value = replace
}

// // 滚动到指定行
// const scrollToTableRow=(tableElement,rowIndex)=>{
//     const theTableRows = tableElement.$el.querySelectorAll('.el-table__body tbody .el-table__row')
//     let scrollTop = 0
//     for (let i = 0; i < theTableRows.length; i++) {
//         if (i === rowIndex) {
//             break
//         }
//         scrollTop += theTableRows[i].offsetHeight
//     }
//     tableElement.scrollTo({top:scrollTop-200,behavior: "smooth"});
// }
// // 滚动到选中接口
// watch(()=>highlightRow.value,(newValue,oldValue)=>{
//     if(newValue && newValue != oldValue){
//         // TODO
//         // const tableElement=proxy.$refs.deptTable?.$refs.deptTable
//         // if(tableElement){
//         //     scrollToTableRow(tableElement,newValue.rowIndex)
//         // }

//     }
// })

getList();
handlefirst()

</script>
<style scoped>
.el-row {
  display: flex;
  flex-wrap: wrap;
  position: relative;
  box-sizing: border-box;
  width: 100%;
}

/deep/ .jsoneditor-menu a {
  color: #3883fa !important;
  /*display: none*/
}

/deep/ .jsoneditor {
  border: thin solid #ffffff !important;

}

</style>
<style lang="scss" scoped>
.app-container {
  padding: 6px !important;
}

.app-container-content {
  height: 100%;

  .interface-tree {
    height: 100%;

    :deep(.el-card__body) {
      height: 100%;
      display: flex;
      flex-direction: column;
    }
  }

  .interface-container {
    position: relative;

    .el-tabs.page-tabs {
      display: flex;
      flex-direction: column;

      :deep(>.el-tabs__header) {
        padding-right: 225px;
        margin-bottom: 10px;
      }

      :deep(.el-tabs__content) {
        // display:flex
        flex: 1;

        .el-tab-pane {
          height: 100%;
          // overflow:auto;
        }
      }
    }

    & > .el-row {
      height: 100%;
      display: flex;
      flex-direction: column;

      & > .el-row:last-child {
        flex: 1;

        .el-card {
          height: 100%;
        }
      }
    }
  }

  .interface-response {
    height: 100%;

    :deep(.el-card__body) {
      height: 100%;
      display: flex;
      flex-direction: column;

      & > .el-row:last-child {
        flex: 1;
      }
    }

    .interface-response-tabs {
      display: flex;
      flex-direction: column;
      width: 100%;

      :deep(.el-tabs__content) {
        flex: 1;

        .el-tab-pane {
          height: 100%;

          .el-form {
            height: 100%;
            display: flex;
            flex-direction: column;

            .el-form-item:last-child {
              flex: 1;

              .container.editor, .el-textarea, .el-textarea__inner {
                height: 100%;
              }
            }
          }
        }
      }
    }
  }

  .interface-request {
    :deep(.el-card__body) {
      height: 100%;

      & > .el-row {
        height: 100%;
        width: 100%;

        .el-tabs {
          height: 100%;
          width: 100%;
          display: flex;
          flex-direction: column;

          .el-tabs__content {
            flex: 1;

            .el-tab-pane {
              height: 100%;

              .el-form {
                height: 100%
              }
            }
          }
        }
      }
    }

    .interface-request-form {
      width: 100%;
      display: flex;
      flex-direction: column;

      :deep(.el-form-item:last-child) {
        flex: 1;

        .container.editor {
          height: 100%;
        }
      }
    }
  }
}

:deep(div.jsoneditor-outer.has-main-menu-bar) {
  margin-bottom: -35px !important;
  padding-bottom: 35px !important;
}

.center-top {
  margin: auto;
  width: 90%;
  padding: 5px;
}


.hover-effect {
  color: black; /* 初始字体颜色 */
}

.hover-effect:hover {
  color: #409eff; /* 鼠标放上去后的字体颜色 */
}

.table-container {
  flex: 1 0 300px;
  overflow: hidden;
  position: relative;
  width: 100%;
  height: auto;
}


.api-environment-input {
  display: flex;
  align-items: center;
  position: absolute;
  right: 5px;
  height: 40px;
  z-index: 1
}

.environment {
  margin-left: 100px;
}

</style>
